package com.nl.utils.pipeline;

import com.nl.model.model.ResponseVO;

/**
 * NormalPipeLine.
 *
 * @author dell
 */
public class NormalPipeLineFactory<T extends PipeLineContext> {

    protected PipeLineValve<T> head;

    protected PipeLineValve<T> next;

    /**
     * 添加执行链路.
     *
     * @param valve 执行链路.
     */
    public void addValve(final PipeLineValve<T> valve) {
        if (head == null) {
            head = valve;
            valve.setNext(next);
        } else {
            PipeLineValve current = head;
            while (current != null) {
                if (current.getNext() == next) {
                    current.setNext(valve);
                    valve.setNext(next);
                    break;
                }
                current = current.getNext();
            }
        }
    }

    /**
     * 开始执行.
     *
     * @param pipeLineContext 容器上下文.
     * @return
     */
    public ResponseVO start(final T pipeLineContext) {
        if (pipeLineContext == null) {
            return ResponseVO.fail("pipeLineContext should be not null!");
        }
        if (head == null) {
            return ResponseVO.fail("there's no valve in current pipeLine!");
        }
        return head.invoke(pipeLineContext);
    }

}
